package com.fulu.game.bi.service.impl.auth;

import com.fulu.game.bi.redis.enums.RedisKeyEnum;
import com.fulu.game.bi.redis.service.RedisOpenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author libo
 * @date 2020/7/30 5:38 PM
 */
@Slf4j
@Service
public class TokenService {

    @Autowired
    private RedisOpenService redisOpenService;

    public static final long DEFAULT_EXPIRE_TIME = 15 * 60;

    public boolean isExists(String token) {
        boolean isExists = redisOpenService.hasKey(generalTokenKey(token));

        if (log.isDebugEnabled()) {
            log.debug("token {} 是否存在: {}", token, isExists);
        }

        return isExists;
    }

    public void refreshToken(String token) {
        expire(token, DEFAULT_EXPIRE_TIME);

    }

    /**
     * 根据token生成redis的key
     * @param token
     * @return
     */
    private String generalTokenKey(String token) {
        return RedisKeyEnum.BI_PLAY_TOKEN.generateKey(token);
    }

    public Map<String, Object> getUserMapBy(String token) {
        Map<String, Object> userMap = redisOpenService.hget(generalTokenKey(token));

        if (log.isDebugEnabled()) {
            log.debug("根据token {} 获取到用户信息 {} ", token, userMap);
        }

        return userMap;
    }

    public void updateUserMap(String token, Map<String, Object> userMap) {
        String tokenKey = generalTokenKey(token);
        redisOpenService.hset(tokenKey, userMap);


        int userId = (int) userMap.get("id");

        if (log.isDebugEnabled()) {
            log.debug("更新token {} , 对应用户信息为 {}", token, userMap);
        }
    }
    public void createUserMap(String token, Map<String, Object> userMap) {
        String tokenKey = generalTokenKey(token);
        redisOpenService.hset(tokenKey, userMap, DEFAULT_EXPIRE_TIME);

        if (log.isDebugEnabled()) {
            log.debug("新增token {}, 对应用户信息为 {}, token过期时间为 {},   时间单位是 {}.",
                    token, userMap, DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS.name());
        }
    }

    public void expire(String token, long expire) {
        String tokenKey = generalTokenKey(token);
        redisOpenService.expire(tokenKey, expire);

        if (log.isDebugEnabled()) {
            log.debug("设置token {} 的过期时间, 过期时间为 {} , 时间单位是 {}", token, expire, TimeUnit.SECONDS.name());
        }
    }

    public void delete(String token) {
        String tokenKey = generalTokenKey(token);

        redisOpenService.delete(tokenKey);

        if (log.isDebugEnabled()) {
            log.debug("删除token {}", token);
        }
    }

}
